package com.crm.sys.handler;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.crm.im.core.constant.IMConstant;
import com.crm.im.core.handler.IMRequestHandler;
import com.crm.im.core.model.Message;
import com.crm.im.core.model.ReplyBody;
import com.crm.im.core.model.SentBody;
import com.crm.im.core.session.DefaultSessionManager;
import com.crm.im.core.session.IMSession;
import com.crm.sys.push.SystemMessagePusher;

/**
 * 断开连接，清除session
 * 
 */
@Service("sessionClosedHandler")
public class SessionClosedHandler implements IMRequestHandler {
	@Autowired
	private DefaultSessionManager sessionManager; 
	@Autowired
	private SystemMessagePusher systemMessagePusher;

	protected final Logger logger = Logger.getLogger(SessionClosedHandler.class);

	public ReplyBody process(IMSession ios, SentBody message) {
		if(ios.getAttribute(IMConstant.SESSION_KEY)==null)
		{
			return null;
		}
	    String account = ios.getAttribute(IMConstant.SESSION_KEY).toString();
	    if(!account.equals(1)){
	    	sessionManager.remove(account);
	       
	    	//通知下线线消息
			List<IMSession>  sessionList = sessionManager.queryAll();
			for(IMSession s:sessionList){
				Message  msg = new Message();
				msg.setType(IMConstant.MessageType.TYPE_OFFLINE);//强行下线消息类型
				msg.setReceiver(s.getAccount());
				msg.setContent(account);
				systemMessagePusher.push(msg); 
			}
	    }
		return null;
	}
	
 
	
}